<?php
include_once dirname(dirname(__FILE__)) . '/include/common.php';
$core = new core();
$zen_order_id = isset($_POST["zen_order_id"]) ? intval($_POST["zen_order_id"]) : 0;
$customer_order_id = isset($_POST["customer_order_id"]) ? intval($_POST["customer_order_id"]) : 0;
if ($core->checkZenOrderByID($zen_order_id)) {

    //insert customer order
    $customer_fb_name = isset($_POST["customer_fb_name"]) ? addslashes(trim($_POST["customer_fb_name"])) : '';
    $customer_name = isset($_POST["customer_name"]) ? addslashes(trim($_POST["customer_name"])) : '';
    $customer_email = isset($_POST["customer_email"]) ? addslashes(trim($_POST["customer_email"])) : '';
    $customer_phone = isset($_POST["customer_phone"]) ? addslashes(trim($_POST["customer_phone"])) : '';
    $customer_address = isset($_POST["customer_address"]) ? addslashes(trim($_POST["customer_address"])) : '';
    $customer_province = isset($_POST["customer_province"]) ? intval($_POST["customer_province"]) : 0;
    $customer_wholesale = isset($_POST["customer_wholesale"]) ? intval($_POST["customer_wholesale"]) : 0;
    $order_description = isset($_POST["order_description"]) ? addslashes(trim($_POST["order_description"])) : '';
    $type_calculate_payment = isset($_POST["type_calculate_payment"]) ? addslashes(trim($_POST["type_calculate_payment"])) : 'normal';//normal, pt , at
    if($type_calculate_payment=='pt'){
        $percent_service = isset($_POST["percent_service"]) ? floatval($_POST["percent_service"]) : 0;
        $fee_weight = isset($_POST["fee_weight"]) ? floatval($_POST["fee_weight"]) : 0;
        $weight = isset($_POST["input_weight"]) ? floatval($_POST["input_weight"]) : 0;
    }else{
        $percent_service = 0;
        $fee_weight = 0;
        $weight = 0;
    }

    if($type_calculate_payment=='pt' || $type_calculate_payment=='at'){
        $exchange_value = isset($_POST["exchange_money"]) ? $_POST["exchange_money"] : 0;
        $exchange_value = floatval(str_replace(",",".",$exchange_value));
        $exchange_value = $exchange_value*1000;
        if($exchange_value < 0){
            echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền tỉ giá > 0!"));
            die;
        }
    }else{
        $exchange_value = 0;

    }

    $list_product_id = isset($_POST["list_product_id"]) ? json_decode(stripslashes($_POST['list_product_id'])) : array();
    $list_product_number = isset($_POST["list_product_number"]) ? json_decode(stripslashes($_POST["list_product_number"])) : array();
    $list_product_size = isset($_POST["list_product_size"]) ? json_decode(stripslashes($_POST["list_product_size"])) : array();
    $list_product_color = isset($_POST["list_product_color"]) ? json_decode(stripslashes($_POST["list_product_color"])) : array();
    $list_product_price = isset($_POST["list_product_price"]) ? json_decode(stripslashes($_POST["list_product_price"])) : array();
    $list_product_description = isset($_POST["list_product_description"]) ? json_decode(stripslashes($_POST["list_product_description"])) : array();
    $list_product_status = isset($_POST["list_product_status"]) ? json_decode(stripslashes($_POST["list_product_status"])) : array();
    $list_zcod_id = isset($_POST["list_zcod_id"]) ? json_decode(stripslashes($_POST["list_zcod_id"])) : array();
    $list_customer_order_date = isset($_POST["list_customer_order_date"]) ? json_decode(stripslashes($_POST["list_customer_order_date"])) : array();
    $list_received_date = isset($_POST["list_received_date"]) ? json_decode(stripslashes($_POST["list_received_date"])) : array();
    $list_saled_date = isset($_POST["list_saled_date"]) ? json_decode(stripslashes($_POST["list_saled_date"])) : array();
    $list_online_date = isset($_POST["list_online_date"]) ? json_decode(stripslashes($_POST["list_online_date"])) : array();
    $list_store_date = isset($_POST["list_store_date"]) ? json_decode(stripslashes($_POST["list_store_date"])) : array();
    $list_price_pt = isset($_POST["list_price_pt"]) ? json_decode(stripslashes($_POST["list_price_pt"])) : array();
    $list_price_at = isset($_POST["list_price_at"]) ? json_decode(stripslashes($_POST["list_price_at"])) : array();
    if(count($list_product_id)==count($list_product_number)
    && count($list_product_number) == count($list_product_size)
    && count($list_product_size)==count($list_product_color)
    && count($list_product_color) == count($list_product_price)
    && count($list_product_price) == count($list_product_description)
    && count($list_product_description) == count($list_product_status)
    && count($list_product_status) == count($list_zcod_id)
    && count($list_zcod_id) == count($list_customer_order_date)
    && count($list_customer_order_date) == count($list_received_date)
    && count($list_received_date) == count($list_saled_date)
    && count($list_saled_date)== count($list_online_date)
    && count($list_online_date) == count($list_store_date)
    && count($list_store_date) == count($list_price_pt)
    && count($list_price_pt) == count($list_price_at)){
        //do nothing
    }else{
        echo json_encode(array('type' => 1, 'msg' => "Có lỗi dữ liệu, vui lòng liên hệ kĩ thuật xử lý!"));
        die;
    }
    //var_dump($_POST);die();
    if ($customer_fb_name == "") {
        echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền tên khách hàng!"));
        die;
    }
    if ($customer_phone == "") {
        echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền số điện thoại!"));
        die;
    } elseif (!ctype_digit($customer_phone)) {
        echo json_encode(array('type' => 1, 'msg' => "Vui lòng chỉ điền số vào ô điện thoại!"));
        die;
    }


    $customer = $core->getCustomerInfoByPhone(addslashes($customer_phone));
    if ($customer) {
        //update customer info
        $core->db->query("UPDATE zen_customer SET facebook_name='$customer_fb_name',address='$customer_address',
            province=$customer_province,name='$customer_name',email='$customer_email',wholesale=$customer_wholesale WHERE phone='$customer_phone'");
        $customer_id = $customer->customer_id;
    } else {
        $core->db->query("INSERT INTO zen_customer (facebook_name,phone,address,province,name,email,wholesale)
                        VALUES('$customer_fb_name','$customer_phone','$customer_address',$customer_province,'$customer_name','$customer_email',$customer_wholesale)");
        $customer_id = $core->db->insert_id;
    }


    if ($customer_id > 0) {
        //kiem tra đơn hàng này tồn tại chưa?
        // $get_customer_order = $core->db->get_row("SELECT * FROM zen_customer_order WHERE customer_id=$customer_id AND zen_order_id= $zen_order_id ");
        $get_customer_order = $core->db->get_row("SELECT * FROM zen_customer_order WHERE customer_order_id=$customer_order_id");
        $old_total_payment = 0;
        //if ($get_customer_order && $customer_order_id > 0) {
        if ($get_customer_order) {
            //edit đơn hàng của khách
            $old_total_payment = $get_customer_order->total_payment;
            $customer_order_detail_ids = $core->getListCustomerOrderDetailId($customer_order_id);
            // tôn tại thì kiểm tra sp nào không có trong list sp client gửi lên thì xóa đi
            if(is_array($customer_order_detail_ids)) {
                foreach ($customer_order_detail_ids as $id) {
                    if (!in_array($id, $list_zcod_id)) {
                        $core->db->query("DELETE FROM zen_customer_order_detail WHERE id=$id AND customer_order_id=$customer_order_id");
                    }
                }
            }

            //delete info of this customer order
            // $del_order = $core->db->query("DELETE FROM zen_customer_order WHERE customer_order_id=$customer_order_id");
            // $del_order_detail = $core->db->query("DELETE FROM zen_customer_order_detail WHERE customer_order_id=$customer_order_id");
//            if (!$del_order || !$del_order_detail) {
//                echo json_encode(array('type' => 1, 'msg' => "Lưu đơn hàng thất bại, vui lòng thử lại!"));
//                die;
//            }
        }
        //if (!$get_customer_order || ($get_customer_order && $customer_order_id == 0)) {

        $exchange = $core->db->get_row("SELECT * FROM zen_exchange ORDER BY id DESC LIMIT 1");

        if (!$get_customer_order) {
            if($exchange_value==0) {
                //type payment normal
                $exchange_value = $exchange->exchange;
            }
            //khach hang mua hang lan dau trong dot hang nay hoac khach hang order them sp ma khong qua edit order co san
            //tao moi customer order
            $random_code = $core->generateRandomString(20);
            $create_time = date('Y-m-d H:i:s');
            $core->db->query("INSERT INTO zen_customer_order (zen_order_id,customer_id,order_description,code_view,
                          `type_calculate_payment`,service_percent,fee_per_kg,weight,exchange,created_time,modified_time)
                        VALUES($zen_order_id,$customer_id,'$order_description','$random_code',
                        '$type_calculate_payment',$percent_service,$fee_weight,$weight,$exchange_value,'$create_time','$create_time')");

            $new_customer_order_id = $core->db->insert_id;
        } else {
            if($exchange_value==0) {
                //type payment normal
                $exchange_value = $get_customer_order->exchange;
            }

            $new_customer_order_id = $get_customer_order->customer_order_id;
            $modify_time = date('Y-m-d H:i:s');
            $core->db->query("UPDATE  zen_customer_order SET
                                    order_description='$order_description',
                                    type_calculate_payment='$type_calculate_payment',
                                    service_percent = $percent_service,
                                    fee_per_kg = $fee_weight,
                                    weight = $weight,
                                    exchange = $exchange_value,
                                    modified_time = '$modify_time'
                                     WHERE customer_order_id=$new_customer_order_id");

        }



        if ($new_customer_order_id > 0) {
            $total_money = 0;
            $total_at = 0;
            $total_pt = 0;
            //save order detail
            for ($i = 0; $i < count($list_product_id); $i++) {

                $price = floatval(preg_replace('/[^\d.]/', '', $list_product_price[$i]));
                $price = $price * 1000;
                $store_price = floatval(preg_replace('/[^\d.]/', '', $list_price_pt[$i]));
                $stamp_price = floatval(preg_replace('/[^\d.]/', '', $list_price_at[$i]));
                //update AT,PT for product
               // $core->db->query("UPDATE zen_product SET store_price=$store_price,stamp_price=$stamp_price WHERE product_id= $list_product_id[$i]");
                if ($list_customer_order_date[$i] != "") {
                    $customer_order_date = addslashes($list_customer_order_date[$i]);
                } else {
                    $customer_order_date = date("Y-m-d H:i:s", time());
                }

                // if (!$get_customer_order || ($get_customer_order && $customer_order_id == 0)) {
                if (!$get_customer_order) {
                    //khach hang mua hang lan dau trong dot hang nay hoac khach hang order them sp ma khong qua edit order co san
                    //tao moi customer order
                    $core->db->query("INSERT INTO zen_customer_order_detail 
                (customer_order_id,product_id,product_size,product_color,
                product_num,order_product_num,product_price,store_price,stamp_price,description,order_status,product_available,
                customer_order_date,received_date,saled_date,online_date,store_date)
                        VALUES($new_customer_order_id,$list_product_id[$i],'" . addslashes($list_product_size[$i]) . "','" . addslashes($list_product_color[$i]) . "',
                        " . intval($list_product_number[$i]) . "," . intval($list_product_number[$i]) . "," . $price . "," . $store_price . "," . $stamp_price . ",'" . addslashes($list_product_description[$i]) . "'," . intval($list_product_status[$i]) . ",0,
                          '" . $customer_order_date . "', '" . addslashes($list_received_date[$i]) . "',
                           '" . addslashes($list_saled_date[$i]) . "','" . addslashes($list_online_date[$i]) . "',
                               '" . addslashes($list_store_date[$i]) . "')");

                    $total_money += intval($list_product_number[$i]) * $price;
                    $total_at+= intval($list_product_number[$i]) *floatval($stamp_price);
                    $total_pt+= intval($list_product_number[$i]) *floatval($store_price);
                } else {
                    //edit, them moi sp vao order có san
                    $customer_order_detail_ids = $core->getListCustomerOrderDetailId($customer_order_id);
                    if (!is_array($customer_order_detail_ids)) {
                        $customer_order_detail_ids = array();
                    }
                    if (in_array($list_zcod_id[$i], $customer_order_detail_ids)) {
                        //update sp da mua
                        if($list_product_status[$i]==6){
                            //trang thai het hang thi ko update ji
                        }else{
                            $check_edit_bought_product_num = $core->db->get_row("SELECT * FROM zen_customer_order_detail WHERE id=$list_zcod_id[$i]");
                            if($check_edit_bought_product_num->is_edit_bought_product_num == 0) {
                                //số lượng sản phẩm đã mua được chưa được sửa, vẫn lấy = số lượng khách đặt
                                $core->db->query("UPDATE zen_customer_order_detail SET product_id= $list_product_id[$i],
                            product_size='" . addslashes($list_product_size[$i]) . "',product_color='" . addslashes($list_product_color[$i]) . "',
                            product_num=" . intval($list_product_number[$i]) . ",order_product_num=" . intval($list_product_number[$i]) . ",product_price=$price,store_price=$store_price,stamp_price=$stamp_price,
                            description='" . addslashes($list_product_description[$i]) . "',
                            order_status=" . intval($list_product_status[$i]) . "
                                WHERE id=$list_zcod_id[$i]");

                                $total_money += intval($list_product_number[$i]) * $price;
                                $total_at += intval($list_product_number[$i]) * floatval($stamp_price);
                                $total_pt += intval($list_product_number[$i]) * floatval($store_price);
                            }else{
                                //chỉ cập nhât số lượng khách đặt
                                $core->db->query("UPDATE zen_customer_order_detail SET product_id= $list_product_id[$i],
                            product_size='" . addslashes($list_product_size[$i]) . "',product_color='" . addslashes($list_product_color[$i]) . "',
                            order_product_num=" . intval($list_product_number[$i]) . ",product_price=$price,store_price=$store_price,stamp_price=$stamp_price,
                            description='" . addslashes($list_product_description[$i]) . "',
                            order_status=" . intval($list_product_status[$i]) . "
                                WHERE id=$list_zcod_id[$i]");

                                //tổng tiền tính theo số sản phẩm đã mua được
                                $total_money += intval($check_edit_bought_product_num->product_num) * $price;
                                $total_at += intval($check_edit_bought_product_num->product_num) * floatval($stamp_price);
                                $total_pt += intval($check_edit_bought_product_num->product_num) * floatval($store_price);
                            }
                        }

                    } else {
                        //them moi sp vao order
                        $core->db->query("INSERT INTO zen_customer_order_detail 
                (customer_order_id,product_id,product_size,product_color,
                product_num,order_product_num,product_price,store_price,stamp_price,description,order_status,product_available,
                customer_order_date,received_date,saled_date,online_date,store_date)
                        VALUES($new_customer_order_id,$list_product_id[$i],'" . addslashes($list_product_size[$i]) . "','" . addslashes($list_product_color[$i]) . "',
                        " . intval($list_product_number[$i]) . "," . intval($list_product_number[$i]) . "," . $price . "," . $store_price . "," . $stamp_price . ",'" . addslashes($list_product_description[$i]) . "'," . intval($list_product_status[$i]) . ",0,
                          '" . $customer_order_date . "', '" . addslashes($list_received_date[$i]) . "',
                           '" . addslashes($list_saled_date[$i]) . "','" . addslashes($list_online_date[$i]) . "',
                               '" . addslashes($list_store_date[$i]) . "')");

                        $total_money += intval($list_product_number[$i]) * $price;
                        $total_at+= intval($list_product_number[$i]) *floatval($stamp_price);
                        $total_pt+= intval($list_product_number[$i]) *floatval($store_price);
                    }
                }
            }
            //update money order
            //calculate total order money

            $total_order_money = 0;
            switch($type_calculate_payment){
                case 'normal':
                    $total_order_money = $total_money;
                    break;
                case 'at':
                    $total_order_money = $exchange_value*$total_at;
                    break;
                case 'pt':
                    //tong PT + 5%PT + 12EU*weight
                    $total_order_money = $exchange_value*($total_pt + $total_pt*$percent_service/100 + $fee_weight*$weight);
                    break;
            }
            //if ($get_customer_order && $customer_order_id > 0) {
            if ($get_customer_order) {
                //them moi sp nhung ton tai don hang cua khach, update money
                $total_payment = $get_customer_order->total_payment;
                $total_current_money = $get_customer_order->total_payment - $total_order_money;
            } else {
                //khach hang chua mua trong dot hang nay
                $total_payment = 0;
                $total_current_money = $total_order_money * (-1);
            }

            //update table customer order
            $total_order_money = core::roundingMoney($total_order_money);
            $total_payment = core::roundingMoney($total_payment);
            $total_current_money = core::roundingMoney($total_current_money);

            $core->db->query("UPDATE zen_customer_order SET total_order_money=$total_order_money,
                        total_store_price = $total_pt,
                        total_stamp_price = $total_at,
                        total_payment = $total_payment,
                        total_current_money= $total_current_money                    
                            WHERE customer_order_id=$new_customer_order_id");
            //update customer order status
//            $core->db->query("UPDATE zen_customer_order 
//SET customer_order_status = (CASE (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id.")
//     WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=0 ) THEN 0
//     WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=1 ) THEN 1
//      WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=2 ) THEN 2
//       WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=3 ) THEN 3
//      WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=4 ) THEN 4
//      WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=5 ) THEN 5
//       WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=6 ) THEN 6
//        WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=7 ) THEN 7
//      WHEN (SELECT COUNT(id) FROM zen_customer_order_detail zcod WHERE zcod.customer_order_id=".$new_customer_order_id." AND order_status=8 ) THEN 8
//     ELSE 9 END
//) WHERE customer_order_id=".$new_customer_order_id);
            //thêm tiền cọc với đơn hàng thêm lần đầu
            if ($customer_order_id == 0) {
                $payment = isset($_POST["payment"]) ? $_POST["payment"] : 0;

                $payment = floatval(preg_replace('/[^\d.]/', '', $payment));
                $payment = $payment * 1000;
                if ($payment > 0) {
                    $type_payment = isset($_POST["type_payment"]) ? intval($_POST["type_payment"]) : 1;
                    $description = isset($_POST["payment_description"]) ? addslashes(trim($_POST["payment_description"])) : '';
                    $payment_date = isset($_POST["payment_date"]) ? addslashes(trim($_POST["payment_date"])) : '';
                    $payment_date = date('Y-m-d', strtotime($payment_date));
                    if ($type_payment != 1 && $type_payment != 2) {
                        $type_payment = 1;
                    }
                    $payment = core::roundingMoney($payment);
                    $new_payment = $payment;

                    $core->db->query("INSERT INTO zen_payment (customer_order_id,payment,type_payment,description,date_payment)
                        VALUES($new_customer_order_id,$payment,$type_payment,'$description','$payment_date')");

                    if ($core->db->insert_id > 0) {
                        //update total_payment,total_current_money
                        $customer_order_data = $core->getZenCustomerOrderById($new_customer_order_id);
                        $total_payment = $customer_order_data->total_payment + $new_payment;
                        $total_payment = core::roundingMoney($total_payment);
                        $total_current_money = $customer_order_data->total_current_money + $new_payment;
                        $total_current_money = core::roundingMoney($total_current_money);

                        $core->db->query("UPDATE zen_customer_order SET total_payment=$total_payment,
                        total_current_money= $total_current_money
                            WHERE customer_order_id=$new_customer_order_id");

                    } else {
                        echo json_encode(array('type' => 0, 'msg' => "Thêm payment thất bại!"));
                        die;
                    }
                }
            }
            echo json_encode(array('type' => 0, 'msg' => "Lưu đơn hàng thành công!"));
            die;
        } else {
            echo json_encode(array('type' => 1, 'msg' => "Lưu đơn hàng thất bại!"));
            die;
        }
    } else {
        echo json_encode(array('type' => 1, 'msg' => "Không lưu được thông tin khách hàng!"));
        die;
    }
} else {
    echo json_encode(array('type' => 1, 'msg' => "Đợt hàng về không tồn tại!"));
    die;
}
?>